package dji.ux.ext.panel.camera;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import dji.common.bus.UXSDKEventBus;
import dji.common.camera.SettingsDefinitions;
import dji.common.error.DJIError;
import dji.common.util.CommonCallbacks;
import dji.sdk.camera.Lens;
import dji.thirdparty.io.reactivex.android.schedulers.AndroidSchedulers;
import dji.thirdparty.rx.subscriptions.CompositeSubscription;
import dji.ux.beta.R;
import dji.ux.beta.base.ConstraintLayoutWidget;
import dji.ux.beta.base.DJISDKModel;
import dji.ux.beta.base.uxsdkkeys.ObservableInMemoryKeyedStore;
import dji.ux.ext.base.UXEEvents;


/**
 * 适配h20/h20T相机的Zoom
 */
public class CameraH20TZoomPanel extends ConstraintLayoutWidget {
    private Lens zoomLens;
    private TextView tvZoomT;
    private TextView tvZoomW;
    private TextView tvZoomR;
    private TextView tvZoomNum;
    private Handler handler = new Handler();
    private Handler uiHandle = new Handler();
    private CameraH20TZoomModel widgetModel;
    private CompositeSubscription subscription = new CompositeSubscription();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            updateH20THybridZoomNum();
            handler.postDelayed(this, 100);
        }
    };

    public CameraH20TZoomPanel(@NonNull Context context) {
        super(context);
    }

    public CameraH20TZoomPanel(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CameraH20TZoomPanel(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void initView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        View view = inflate(context, R.layout.ext_panel_h20t_zoom, this);
        tvZoomT = view.findViewById(R.id.tv_zoom_t);
        tvZoomW = view.findViewById(R.id.tv_zoom_w);
        tvZoomR = view.findViewById(R.id.tv_zoom_r);
        tvZoomNum = view.findViewById(R.id.tv_zoom_number);
        addH20TClickListener();

        if (!isInEditMode()) {
            widgetModel = new CameraH20TZoomModel(DJISDKModel.getInstance(),
                    ObservableInMemoryKeyedStore.getInstance());
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (!isInEditMode()) {
            widgetModel.setup();
        }

        this.subscription.add(UXSDKEventBus.getInstance().
                register(UXEEvents.CameraZoomVisibility.class)
                .observeOn(dji.thirdparty.rx.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(var1 -> {
                    if (var1 == UXEEvents.CameraZoomVisibility.GONE)
                        setVisibility(GONE);
                    else if (var1 == UXEEvents.CameraZoomVisibility.SHOW)
                        setVisibility(VISIBLE);
                }));
    }

    @Override
    protected void onDetachedFromWindow() {
        if (!isInEditMode()) {
            widgetModel.cleanup();
        }
        super.onDetachedFromWindow();
    }

    @Override
    protected void reactToModelChanges() {
        addReaction(widgetModel.getProductConnection()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::isProductConnected));
    }

    @NonNull
    @Override
    public String getIdealDimensionRatioString() {
        return null;
    }

    /**
     * auto show/hide widget when product connecting status changed
     *
     * @param isConnected is Product connected
     */
    private void isProductConnected(Boolean isConnected) {
        if (isConnected != null && isConnected) {
            if (widgetModel.isH20TCamera()) {
                setVisibility(VISIBLE);
                zoomLens = widgetModel.getZoomLens();
                updateH20THybridZoomNum();
            } else {
                setVisibility(GONE);
            }
        } else {
            setVisibility(GONE);
        }
    }

    private void updateH20THybridZoomNum() {
        if (zoomLens == null)
            return;

        zoomLens.getHybridZoomFocalLength(new CommonCallbacks.CompletionCallbackWith<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                uiHandle.post(() -> {
                    String temp = String.format("%.1f", (float) (integer) / 317) + "x";
                    tvZoomNum.setText(temp);
                });
            }

            @Override
            public void onFailure(DJIError djiError) {

            }
        });
    }

    private void addH20TClickListener() {
        //放大聚焦
        tvZoomT.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    tvZoomT.setPressed(true);
                    handler.postDelayed(runnable, 100);
                    zoomLens.startContinuousOpticalZoom(SettingsDefinitions.ZoomDirection.ZOOM_IN, SettingsDefinitions.ZoomSpeed.NORMAL, null);
                    break;
                case MotionEvent.ACTION_MOVE:
                    tvZoomT.setPressed(true);
                    break;
                case MotionEvent.ACTION_UP:
                    tvZoomT.performClick();
                    tvZoomT.setPressed(false);
                    zoomLens.stopContinuousOpticalZoom(null);
                    handler.removeCallbacks(runnable);
                    updateH20THybridZoomNum();
                    break;
                default:
                    break;
            }
            return true;
        });

        //缩小聚焦
        tvZoomW.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    handler.postDelayed(runnable, 100);
                    tvZoomW.setPressed(true);
                    zoomLens.startContinuousOpticalZoom(SettingsDefinitions.ZoomDirection.ZOOM_OUT, SettingsDefinitions.ZoomSpeed.NORMAL, null);
                    break;
                case MotionEvent.ACTION_MOVE:
                    tvZoomW.setPressed(true);
                    break;
                case MotionEvent.ACTION_UP:
                    tvZoomW.performClick();
                    tvZoomW.setPressed(false);
                    zoomLens.stopContinuousOpticalZoom(null);
                    handler.removeCallbacks(runnable);
                    updateH20THybridZoomNum();
                    break;

            }
            return true;
        });

        //恢复初始值
        tvZoomR.setOnClickListener(v -> zoomLens.getHybridZoomSpec(new CommonCallbacks.CompletionCallbackWith<SettingsDefinitions.HybridZoomSpec>() {
            @Override
            public void onSuccess(SettingsDefinitions.HybridZoomSpec hybridZoomSpec) {
                int minFocalLength = hybridZoomSpec.getMinHybridFocalLength();
                zoomLens.setHybridZoomFocalLength(minFocalLength, djiError -> {
                    if (djiError == null) {
                        uiHandle.post(() -> tvZoomNum.setText("1x"));
                    }
                });


            }

            @Override
            public void onFailure(DJIError djiError) {
            }
        }));
    }


}
